package mybatis.generator.plugin.plugins;

import mybatis.generator.plugin.codegen.javamapper.CustomJavaMapperMethodGenerator;
import mybatis.generator.plugin.codegen.xmlmapper.CustomAbstractXmlElementGenerator;
import mybatis.generator.plugin.codegen.xmlmapper.InsertBatchElementMysqlGenerator;
import mybatis.generator.plugin.codegen.xmlmapper.InsertBatchElementOracleGenerator;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.AbstractJavaMapperMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.AbstractXmlElementGenerator;

import java.util.List;
import java.util.Properties;

public class CustomPlugin extends PluginAdapter {

    public static final String MYSQL = "mysql";
    public static final String ORACLE = "oracle";

    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {

        Properties properties = getProperties();
        init(document, introspectedTable, new CustomAbstractXmlElementGenerator());
        if(MYSQL.equals(properties.get("type"))){
            init(document, introspectedTable, new InsertBatchElementMysqlGenerator());
            return super.sqlMapDocumentGenerated(document, introspectedTable);
        }
        if(ORACLE.equals(properties.get("type"))){
            init(document, introspectedTable, new InsertBatchElementOracleGenerator());
            return super.sqlMapDocumentGenerated(document, introspectedTable);
        }
        return false;

    }

    @Override
    public boolean clientGenerated(Interface interfaze, IntrospectedTable introspectedTable) {

        Properties properties = getProperties();
        if(MYSQL.equals(properties.get("type"))||ORACLE.equals(properties.get("type"))){
            AbstractJavaMapperMethodGenerator methodGenerator = new CustomJavaMapperMethodGenerator();
            methodGenerator.setContext(context);
            methodGenerator.setIntrospectedTable(introspectedTable);
            methodGenerator.addInterfaceElements(interfaze);
            return super.clientGenerated(interfaze, introspectedTable);
        }
        return false;
    }

    private void init(Document document, IntrospectedTable introspectedTable, AbstractXmlElementGenerator elementGenerator) {
        elementGenerator.setContext(context);
        elementGenerator.setIntrospectedTable(introspectedTable);
        elementGenerator.addElements(document.getRootElement());
    }
}
